package com.thitech.sif.ws.soap;

import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.handler.Handler;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.rpc.handler.HandlerRegistry;

import com.thitech.sif.utils.log.LogFactory;
import com.thitech.sif.utils.log.SifLogger;

/**
 * RPC客户端注册管理类
 * @author shisheng.lian
 * @date 2014-7-16
 */
public class RPCClientHandlerManager {
	private static SifLogger log = LogFactory.getLogger(RPCClientHandlerManager.class);
	
	/**
	 * 注册WebService客户端服务对象
	 * @param service WebService客户端Proxy服务对象
	 * @param handlerClass PRC Handler对象
	 */
	@SuppressWarnings("unchecked")
	public static void registerHandler(Service service, Class<? extends Handler> handlerClass) {
		registerHandlers(service, handlerClass);
	}

	/**
	 * 注册WebService客户端服务对象
	 * @param service WebService客户端Proxy服务对象
	 * @param handlerClasses PRC Handler对象
	 */
	@SuppressWarnings("unchecked")
	public static void registerHandlers(Service service, Class<? extends Handler>...handlerClasses) {
		if ((service != null) && (handlerClasses != null)
				&& (handlerClasses.length > 0))
			try {
				HandlerRegistry hr = service.getHandlerRegistry();
				if (hr == null) {
					return;
				}
				Iterator<QName> ports = service.getPorts();
				if (ports == null) {
					return;
				}
				do {
					QName portName = ports.next();
					List<HandlerInfo> hc = hr.getHandlerChain(portName);
					if (hc != null) {
						HandlerInfo hi = new HandlerInfo();
						for (Class<? extends Handler> handlerClass : handlerClasses) {
							hi.setHandlerClass(handlerClass);
							hc.add(hi);
						}
					}
				} while (ports.hasNext());
			} catch (ServiceException e) {
				log.error("RPC客户端注册失败", e);
			}
	}
}
